/*
 * 版权所有 (c) 华为技术有限公司 2022-2022
 */
package com.huawei.cameratest.util;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
    public static final String ISP_PATH = "/data/ota_package/";

    public static List<String> getFilesAllName(String path) {
        File file = new File(path);
        try {
            String canonicalPath = file.getCanonicalPath();
            if (!validatePath(canonicalPath)) {
                throw new IllegalArgumentException("Path Traversal vulnerability!");
            }

            File[] files = file.listFiles();
            if (files == null) {
                Log.e("error", "空目录");
                return null;
            }
            List<String> strings = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                String interCanonicalPath = files[i].getCanonicalPath();
                if (!validatePath(interCanonicalPath)) {
                    throw new IllegalArgumentException("Path Traversal vulnerability!");
                }
                strings.add(interCanonicalPath);
            }
            return strings;
        } catch (IOException e) {
            throw new IllegalArgumentException("An exception occurred ...", e);
        }
    }

    private static boolean validatePath(String path) {
        if (path.startsWith(File.separator)) {
            return true;
        } else {
            return false;
        }
    }

    public static String[] getFilesAllName2(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
            Log.e("error", "空目录");
            return null;
        }
        String[] strings = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            strings[i] = files[i].getName();
        }
        return strings;
    }

    public static boolean saveBytes(byte[] bytes, String imagePath) {
        File file = new File(imagePath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            if (!parentFile.mkdirs()) {
                return false;
            }
        }
        try (FileOutputStream fos = new FileOutputStream(file);){
            fos.write(bytes);
            fos.flush();
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
